package com.qianbao.qianbaobusiness.ui.cashier;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidbase.utils.AndroidUtils;
import com.androidbase.utils.ToastUtils;
import com.androidbase.widget.recycleadpter.BaseRecycleViewAdapter;
import com.baseandroid.config.Constant;
import com.baseandroid.config.Global;
import com.baseandroid.mvp.BaseMvpActivity;
import com.baseandroid.utils.TimeUtils;
import com.qianbao.qianbaobusiness.R;
import com.qianbao.qianbaobusiness.help.DateTimePickDialogHelper;
import com.qianbao.qianbaobusiness.json.BalanceAmount2Bean;
import com.qianbao.qianbaobusiness.json.MerchantInfo;
import com.qianbao.qianbaobusiness.ui.cashier.databill.DataBillOldActivity;

import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 历史账单
 */
public class HistoryBalanceActivity extends BaseMvpActivity<HistoryBalanceView, HistoryBalancePresenter>
        implements HistoryBalanceView, SwipeRefreshLayout.OnRefreshListener, BaseRecycleViewAdapter.OnLoadMoreListener, HistoryBalancreAdapter.ClickListener {
    /**
     * 控件相关
     */
    @BindView(R.id.toolbar_back)
    RelativeLayout     toolbarBack;    //返回
    @BindView(R.id.toolbar_title)
    TextView           toolbarTitle;    //标题
    @BindView(R.id.right_image)
    ImageView          rightImage;    //邮箱发送
    @BindView(R.id.start_layout)
    LinearLayout       startLayout;  //开始日期选择
    @BindView(R.id.start_time)
    TextView           tvStartTime;        //开始时间
    @BindView(R.id.end_layout)
    LinearLayout       endLayout;    //结束日期选择
    @BindView(R.id.end_time)
    TextView           tvEndTime;  //结束时间
    @BindView(R.id.swip_history)
    SwipeRefreshLayout mSwrl;    //刷新
    @BindView(R.id.recy_history)
    RecyclerView       mRv;      //列表
    @BindView(R.id.ll_uplayout)
    LinearLayout       ll_uplayout;


    private String                 mStartDate;     //默认开始日期
    private String                 mEndDate;   //默认的结束日期
    private LinearLayoutManager    mLayoutManager;
    private HistoryBalancreAdapter mRvAdapter;
    private String                 mSelectedPosMerchantNo;
    private PopupWindow            popupWindow;   //邮箱发送弹框
    private              int pageNum  = 1;
    private static final int pageSize = 15;
    private boolean isStart;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_history_balance;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void setupView() {
        mSelectedPosMerchantNo = getSelectedPosMerchantNo();
        mStartDate = TimeUtils.getDateNDaysDelay(-11, Constant.DATE_YYYY_MM_DD);
        tvStartTime.setText(mStartDate);
        mEndDate = TimeUtils.getDateNDaysDelay(-1, Constant.DATE_YYYY_MM_DD);
        tvEndTime.setText(mEndDate);
        mSwrl.setEnabled(true);
        mSwrl.setOnRefreshListener(this);
        mSwrl.setColorSchemeColors(ContextCompat.getColor(this, R.color.text_red));
        mRvAdapter = new HistoryBalancreAdapter(this);
        mLayoutManager = new LinearLayoutManager(this);
        mRv.setLayoutManager(mLayoutManager);
        mRv.setAdapter(mRvAdapter);
        mRvAdapter.setOnLoadMoreListener(this, mRv);
        mRvAdapter.setItemClickListener(this);
    }

    private String getSelectedMerchantNos() {
        StringBuilder sb = new StringBuilder();
        for (MerchantInfo merchantInfo : Global.getSelectedShopListInfo().merchantList) {
            if (merchantInfo.isSelected) {
                sb.append(merchantInfo.merchantNo).append(",");
            }
        }
        String merchantNos;
        if (!TextUtils.isEmpty(sb)) {
            merchantNos = sb.substring(0, sb.indexOf(","));
        } else {
            merchantNos = "";
        }
        return merchantNos;
    }

    private String getSelectedPosMerchantNo() {
        String posMerchantNos = "";
        List<MerchantInfo> merchantList = Global.getSelectedShopListInfo().merchantList;
        if (merchantList == null || merchantList.size() == 0) {
            return posMerchantNos;
        } else {
            for (MerchantInfo merchantInfo : merchantList) {
                if (merchantInfo.isSelected) {
                    if (TextUtils.isEmpty(posMerchantNos)) {
                        posMerchantNos = merchantInfo.posMerchantNo;
                    } else {
                        posMerchantNos = posMerchantNos + "," + merchantInfo.posMerchantNo;
                    }
                }
            }
            return posMerchantNos;
        }
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {
        toolbarTitle.setText("账单查询");
        rightImage.setVisibility(View.VISIBLE);
        getBillList();
    }

    @OnClick({R.id.toolbar_back, R.id.right_image, R.id.start_layout, R.id.end_layout})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_back:
                finish();
                break;

            case R.id.right_image:
                SendEmailPopWindow morePopWindow = new SendEmailPopWindow(HistoryBalanceActivity.this, ll_uplayout, TimeUtils
                                                                                                                            .getDate(mStartDate, Constant.DATE_YYYY_MM_DD, Constant.DATE_YYYYMMDD), TimeUtils
                                                                                                                                                                                                            .getDate(mEndDate, Constant.DATE_YYYY_MM_DD, Constant.DATE_YYYYMMDD), "2", new SendEmailPopWindow.onItmeclick() {
                    @Override
                    public void onItemClickListern() {
                        if (TextUtils.isEmpty(Global.getUserInfoBean().getUser().getEmail())) {
                            ToastUtils.showLongToast(AndroidUtils.getContext()
                                                             .getResources()
                                                             .getString(R.string.dont_bind_emile));
                        } else {
                            getPresenter().sendEmail(Constant.HISTORY_TYPE
                                    , TimeUtils.getDate(mStartDate, Constant.DATE_YYYY_MM_DD, Constant.DATE_YYYYMMDD)
                                    , TimeUtils.getDate(mEndDate, Constant.DATE_YYYY_MM_DD, Constant.DATE_YYYYMMDD)
                                    , getSelectedMerchantNos()
                                    , Global.getUserInfoBean().getUser().getUserNo()
                                    , Global.getUserInfoBean().getUser().getEmail());
                        }
                    }
                });
                morePopWindow.showPopupWindow(morePopWindow, rightImage);
                morePopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        ll_uplayout.setVisibility(View.GONE);
                    }
                });

                break;

            case R.id.start_layout:
                isStart = true;
                new DateTimePickDialogHelper(this)
                        .addDatePickListern(new DateTimePickDialogHelper.TimePickListener() {
                            @Override
                            public void date(String date) {
                                mStartDate = date;
                                judgeDate();
                            }
                        })
                        .show(getCalendar(tvStartTime.getText().toString()));
                break;

            case R.id.end_layout:
                isStart = false;
                new DateTimePickDialogHelper(this)
                        .addDatePickListern(new DateTimePickDialogHelper.TimePickListener() {
                            @Override
                            public void date(String date) {
                                mEndDate = date;
                                judgeDate();
                            }
                        })
                        .show(getCalendar(tvEndTime.getText().toString()));
                break;
            default:
                break;
        }
    }

    private Calendar getCalendar(String s) {
        Calendar calendar = Calendar.getInstance();
        String[] arr = s.split("-");
        calendar.set(Integer.parseInt(arr[0]), Integer.parseInt(arr[1]) - 1, Integer.parseInt(arr[2]));
        return calendar;
    }


    private void judgeDate() {
        int numOfDaysStart2Default = TimeUtils.getNumOfDays(mStartDate, Constant.BALANCE_DEFAULT_DAY, Constant.DATE_YYYY_MM_DD);
        int numOfDaysStart2Month = TimeUtils.getNumOfDays(mStartDate
                , TimeUtils.beforeMothDate(-6, Constant.DATE_YYYY_MM_DD), Constant.DATE_YYYY_MM_DD);
        int numOfDaysStart2End = TimeUtils.getNumOfDays(mStartDate, mEndDate, Constant.DATE_YYYY_MM_DD);
        int numOfDaysEnd = TimeUtils.getNumOfDays(mEndDate
                , TimeUtils.getDateNDaysDelay(-1, Constant.DATE_YYYY_MM_DD), Constant.DATE_YYYY_MM_DD);
        if (isStart) {
            if (numOfDaysStart2Default > 0) {   //账单查询不能早于2017-01-01
                ToastUtils.showLongToast(getApplicationContext()
                                                 .getResources().getString(R.string.only_check_to_2017));
                return;
            }
            if (numOfDaysStart2Month > 0) {     //查询账单不能早于半年前
                ToastUtils.showLongToast(getApplicationContext()
                                                 .getResources().getString(R.string.check_half_year));
                return;
            }
            if (numOfDaysStart2End < 0) {   //开始时间不能小于结束时间
                ToastUtils.showLongToast(getApplicationContext()
                                                 .getResources().getString(R.string.start_dont_after_end));
                return;
            }
            tvStartTime.setText(mStartDate);
            pageNum = 1;
            getBillList();
        } else {
            if (numOfDaysEnd < 0) {
                ToastUtils.showLongToast(getApplicationContext()
                                                 .getResources().getString(R.string.date_dont_before_yes));
                return;
            }
            if (numOfDaysStart2End <= 0) {   //开始时间不能小于结束时间
                ToastUtils.showLongToast(getApplicationContext()
                                                 .getResources().getString(R.string.end_dont_before_end));
                return;
            }
            tvEndTime.setText(mEndDate);
            pageNum = 1;
            getBillList();
        }
    }


    private void getBillList() {
        getPresenter().queryDaysCheckedPage(mSelectedPosMerchantNo, pageNum, pageSize, tvStartTime.getText().toString().replaceAll("-", ""), tvEndTime.getText().toString().replaceAll("-", ""));
    }

    @Override
    public void onError(Throwable e) {
        if (mSwrl.isRefreshing()) {
            mSwrl.setRefreshing(false);
        } else {
            mRvAdapter.loadMoreFail();
        }
    }


    @Override
    public void onSuccess(List<BalanceAmount2Bean> list) {
        if (mSwrl.isRefreshing()) {
            mSwrl.setRefreshing(false);
        }
        if (list == null) {
            return;
        }
        if (pageNum == 1) {
            mRvAdapter.resetData(list);
            if (list.size() == 0) {
                mRvAdapter.setEmptyView(R.layout.layout_empty_balance);
                mRvAdapter.loadMoreEnd(false);
            } else if (list.size() < pageSize) {
                mSwrl.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mRvAdapter.loadMoreEnd(true);
                    }
                },200);
            }
        } else {
            if (list.size() == 0) {
                mRvAdapter.loadMoreEnd(false);
                return;
            }
            if (list.size() < pageSize) {
                mRvAdapter.addData(list);
                mRvAdapter.loadMoreComplete();
                mRvAdapter.loadMoreEnd(false);
                return;
            }
            mRvAdapter.addData(list);
            mRvAdapter.loadMoreComplete();
        }
    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        getBillList();
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        getBillList();
    }

    @Override
    public void itemClicked(BalanceAmount2Bean model) {
        Bundle bundle = new Bundle();
        bundle.putString("chkAccountDate", model.getChkAccountDate());
        bundle.putString("postMerchantNo", model.getMerchantCode());
        Intent intent = new Intent(this, DataBillOldActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }
}
